class Solution {
public:
    int n, m;
    vector<vector<bool>> check;
    int ret;
    int numIslands(vector<vector<char>>& grid) {
        n = grid.size(), m = grid[0].size();
        check = vector<vector<bool>>(n, vector<bool>(m));
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == '1' && !check[i][j]) {
                    ret++;
                    dfs(i, j, grid);
                }
            }
        }
        return ret;
    }
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    void dfs(int i, int j, vector<vector<char>>& grid) {
        check[i][j] = true;
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && y >= 0 && x < n && y < m && !check[x][y] &&
                grid[x][y] == '1') {
                dfs(x, y, grid);
            }
        }
    }
};